<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :rules="rules" :inline="true" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属系统" prop="eqptsystem">
            <el-select
              v-model="form.eqptsystem"
              class="input_text"
              placeholder="请先选择所属系统"
              :disabled="isView"
              @change="selectFun"
            >
              <el-option
                v-for="(item, index) in eqptSystemList"
                :key="item.label + index"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="eqpttypeid">
            <el-select
              v-model="form.eqpttypeid"
              allow-create
              filterable
              class="input_text"
              placeholder="请先选择设备类型"
              :disabled="isView"
            >
              <el-option
                v-for="(item, index) in eqptTypeList"
                :key="item.name + index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备编号">
            <el-input v-model="form.eqptcode" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称">
            <el-input v-model="form.eqptname" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备序列号" prop="serialno">
            <el-input v-model="form.serialno" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属客户">
            <el-select v-model="form.customerId" default-first-option placeholder="请选择所属客户" :disabled="isView" style="width: 300px" @change="indexSelect($event)">
              <el-option v-for="(item,index) in customerItem" :key="item.id + index" :label="item.customerName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-select
              v-model="form.brandname"
              allow-create
              filterable
              default-first-option
              class="input_text"
              :disabled="isView"
              placeholder="请先选择品牌"
              @keyup.enter.native="onSubmitBrand"
              @change="selectBrand"
            >
              <el-option
                v-for="(item, index) in eqptbrandlist"
                :key="item.label + index"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号">
            <el-select
              v-model="form.modelname"
              allow-create
              filterable
              default-first-option
              :disabled="isView"
              class="input_text"
              placeholder="请先选择型号"
              @keyup.enter.native="onSubmitModelname"
            >
              <el-option
                v-for="(item, index) in eqptmodelnamelist"
                :key="item.id + index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="资产负责人">
            <el-input v-model="form.header" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人电话">
            <el-input v-model="form.headerphone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产厂家">
            <el-input v-model="form.manufacturer" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购置时间">
            <el-date-picker
              v-model="form.purtime"
              :disabled="isView"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 300px"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商">
            <el-input v-model="form.supplier" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商联系人">
            <el-input v-model="form.suppliercontact" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人电话">
            <el-input v-model="form.suppliercontactphone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="质保期限" prop="warrantytime">
            <el-input v-model="form.warrantytime" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="安装地区" prop="country" :rules="{ required: true, message: '请选择地区' }">
            <AreaSelect ref="areaSelect" :default-props="form" :disabled="isView" @change="handleSelectArea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备状态">
            <el-select v-model="form.eqptstate" class="input_text" placeholder="请先选择设备状态" :disabled="isView">
              <el-option
                v-for="(item, index) in eqptstatelist"
                :key="item.label + index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.eqptdesc" type="textarea" :rows="4" style="width:760px" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              :before-remove="handleBeforeRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-preview="handlePreview"
              :file-list="files"
              :headers="headers"
              :action="imagesUploadApi"
              class="upload-demo"
              :disabled="isView"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" style="display: block;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/tEquipment'
import { getDictDetails, dictDetailAdd } from '@/api/dictDetail'
import { getAllEqptType, add as addEqpttype } from '@/api/tEqpttype'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { del } from '@/api/picture'
import AreaSelect from '@/components/AreaSelect'

export default {
  components: { AreaSelect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      title: '',
      eqptstatelist: [],
      eqptSystemList: [],
      eqptTypeList: [],
      eqptbrandlist: [],
      eqptmodelnamelist: [],
      enabledUploadBtn: true,
      customerItem: [],
      files: [],
      form: {
        id: '',
        eqptsystem: '',
        eqpttypeid: '',
        eqptcode: '',
        eqptname: '',
        brandname: '',
        modelname: '',
        serialno: '',
        header: '',
        headerphone: '',
        manufacturer: '',
        purtime: '',
        supplier: '',
        suppliercontact: '',
        suppliercontactphone: '',
        warrantytime: '',
        address: '',
        eqptdesc: '',
        eqptstate: '',
        customerId: '',
        attachments: '',
        notes: '',
        country: '',
        province: '',
        city: '',
        county: ''
      },
      rules: {
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        eqptsystem: [
          { required: true, message: '请选择所属系统', trigger: 'blur' }
        ],
        eqpttypeid: [
          { required: true, message: '请选择设备类型', trigger: 'blur' }
        ],
        serialno: [
          { required: true, message: '请输入序列号', trigger: 'blur' }
        ],
        country: [
          { required: true, message: '请输入安装地区', trigger: 'blur' }
        ],
        warrantytime: [
          { required: true, message: '请输入质保期限', trigger: 'blur' }
        ]
      },
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 200px'
    } else {
      this.style = 'width: 172px'
    }
    this.tcustmerInfoAll()
  },
  mounted: function() {
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.country = countryItem.name
      this.form.province = provinceItem.name
      this.form.city = cityItem.name
      this.form.county = areaItem.name
    },
    tcustmerInfoAll() {
      this.getAllcustmer().then(res => {
        this.customerItem = res
      })
    },
    getAllcustmer() {
      return request({
        url: 'api/tCustomerInfoAll',
        method: 'get'
      })
    },
    onSubmitBrand() {
      var data = {
        id: '',
        label: this.form.brandname,
        value: this.form.brandname,
        sort: 999,
        dict: { id: 14 }
      }
      dictDetailAdd(data)
        .then(res => {
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    onSubmitModelname() {
      // 先选择品牌，再增加
      if (this.form.brandname) {
        var data = {
          name: this.form.modelname,
          eqptsystemid: this.form.brandname,
          sort: 999,
          dictDetail: { id: this.form.brandname }
        }
        addEqpttype(data)
          .then(res => {
            this.$notify({
              title: '添加成功',
              type: 'success',
              duration: 2500
            })
          })
          .catch(err => {
            this.loading = false
            console.log(err)
          })
      }
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      const _this = this
      this.$refs['form'].validate(valid => {
        if (valid) {
          _this.loading = true
          const fileIds = []

          _this.files.forEach(function(data, index) {
            fileIds.push(data.name) // very important
          })
          _this.form.attachments = fileIds.join(',')
          if (_this.isAdd) {
            _this.doAdd()
          } else {
            _this.doEdit()
          }
        }
      })
    },
    doAdd() {
      add(this.form)
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.$parent.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    doEdit() {
      this.form.purtime = parseTime(this.form.purtime)
      edit(this.form)
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.supThis.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.$refs['areaSelect'] && this.$refs['areaSelect'].clear()
      this.eqptstate = null
      this.form = {
        id: '',
        eqptsystem: '',
        eqpttypeid: '',
        eqptcode: '',
        eqptname: '',
        brandname: '',
        modelname: '',
        serialno: '',
        header: '',
        headerphone: '',
        manufacturer: '',
        purtime: '',
        supplier: '',
        suppliercontact: '',
        suppliercontactphone: '',
        warrantytime: '',
        eqptdesc: '',
        eqptstate: '',
        customerId: '',
        attachments: '',
        notes: '',
        country: '',
        province: '',
        city: '',
        county: ''
      }
      this.files = []
    },
    getEqptStates() {
      getDictDetails('eqpt_status').then(res => {
        this.eqptstatelist = res.content
      })
    },
    getEqptBrand() {
      getDictDetails('eqpt_brand').then(res => {
        this.eqptbrandlist = res.content
      })
    },
    getEqptSystem() {
      getDictDetails('eqpt_system').then(res => {
        this.eqptSystemList = res.content
      })
    },
    changeEqptType(val) {
      this.form.eqpttypeid = val
      this.$forceUpdate()
    },
    getEqptType(systemid) {
      this.eqptTypeList = []
      getAllEqptType(systemid)
        .then(res => {
          this.eqptTypeList = res.content
          var flag = false
          for (var index in this.eqptTypeList) {
            if (this.eqptTypeList[index].id === this.form.eqpttypeid) {
              flag = true
              break
            }
          }
          if (!flag) {
            this.form.eqpttypeid = ''
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getEqptModel(brand) {
      this.eqptmodelnamelist = []
      if (brand) {
        getAllEqptType(brand)
          .then(res => {
            this.eqptmodelnamelist = res.content
            const hasModel = this.eqptmodelnamelist.find(item => item.id === this.form.modelname)
            if (!hasModel) {
              this.form.modelname = ''
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    selectFun(val) {
      this.getEqptType(this.form.eqptsystem)
    },
    // 选择品牌,获取型号
    selectBrand(val) {
      this.getEqptModel(val)
    },
    querySearch(queryString, cb) {
      // this.getCustomers(queryString)
      const params = {
        customerName: queryString
      }
      request({
        url: 'api/tCustomerInfo',
        method: 'get',
        params
      }).then(res => {
        this.faultDevices = []
        this.devices = []
        this.customers = []
        const content = [].concat(res.content)
        const _this = this
        content.forEach(function(data, index) {
          const customer = { id: data.id, value: data.customerName, address: data.address }
          _this.customers.push(customer)
        })
        cb(this.customers)
      }).catch(err => {
        console.log(err)
      })
    },
    indexSelect(event) {
      for (const index in this.customerItem) {
        const item = this.customerItem[index]
        if (item.id === event) {
          this.form.customerName = item.customerName
          return
        }
      }
      this.form.customerName = ''
    },
    // 附件增加成功,name字段用作标识
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.files.push({ uid, name: id, url: '/api/picture/' + id })
    },
    // 删除附件
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < fileList.length; i++) {
        console.log(fileList[i])
        if (fileList[i].name === file.name) {
          del(fileList[i].name).then(res => {
            _this.files.splice(i, 1)
          })
          return true
        }
      }
    },
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px;
}
</style>
